import type { NodejsMirror, NodeVersionInfo } from "@/pages/tools/nodejs/mirror/types";
import { requestGet } from "@/framework/util/http";
import dayjs from "dayjs";
import semver from "semver";
import { getPlatform } from "@/pages/tools/common/util";
import type { NpmMirrorResponse } from "@/pages/tools/common/npmmirror-types";

/**
 * 淘宝npmmirror节点镜像源
 */
const npmmirror: NodejsMirror = {
  name: "npmmirror",
  displayName: "npmmirror.com",
  mirrorUrl: "https://registry.npmmirror.com/-/binary/node/",

  async getVersionList() {
    const resp: NpmMirrorResponse = await requestGet(this.mirrorUrl);
    const versionList: NodeVersionInfo[] = [];
    for (const it of resp.data) {
      if (it.type === "dir" && it.name?.startsWith("v")) {
        versionList.push({
          version: it.name.replace("v", "").replace("/", ""),
          lastModified: dayjs(new Date(it.modified)).format("YYYY-MM-DD"),
        });
      }
    }
    versionList.sort((a, b) => semver.compare(b.version, a.version));
    return versionList;
  },

  getDownloadUrl(version: string) {
    // https://registry.npmmirror.com/-/binary/node/v20.9.0/node-v20.9.0-win-x86.7z
    return `${this.mirrorUrl}v${version}/node-v${version}-${getPlatform()}-${proc.arch}.7z`;
  },
};

export default npmmirror;
